package systems

import (
	"crypto/md5"
	"encoding/hex"
	"errors"
	"fmt"
	"gitee.com/xgh2012/wails_common/wails_apps"
	"gitee.com/xgh2012/wails_common/wails_core"
	"gitee.com/xgh2012/wails_common/wails_core/times"
	"gitee.com/xgh2012/wails_common/wails_utils"
)

// CheckIsRegister 检测是否注册
func CheckIsRegister(name string) error {
	//读取注册表信息
	code, err := wails_utils.GetRegisterRegedit(name)
	if err != nil {
		return err
	}
	fmt.Println(code, err)
	//未注册
	if code == "" {
		IsRegistered = false
		return nil
	}
	if len(code) != 36 {
		return errors.New("注册码格式错误")
	}
	soft, err := wails_utils.GetSoftInfo(wails_apps.SoftName)
	if err != nil {
		IsRegistered = false
		return err
	}

	randomString := code[len(code)-4:]
	res := code[:len(code)-4]
	md := md5.Sum([]byte(soft + wails_apps.SoftName + randomString))
	if hex.EncodeToString(md[:]) != res {
		IsRegistered = false
		return errors.New("硬件信息已改变，请重新注册")
	}

	IsRegistered = true
	return nil
}

// DoRegister 写入
func DoRegister(name, code string) error {
	if len(code) != 36 {
		return errors.New("注册码格式不正确")
	}

	soft, err := wails_utils.GetSoftInfo(wails_apps.SoftName)
	if err != nil {
		return err
	}

	randomString := code[len(code)-4:]
	res := code[:len(code)-4]
	md := md5.Sum([]byte(soft + wails_apps.SoftName + randomString))
	if hex.EncodeToString(md[:]) != res {
		return errors.New("请输入正确的注册码")
	}

	err = wails_utils.SetRegisterRegedit(name, code)
	if err != nil {
		return err
	}
	IsRegistered = true
	IsRegisterMessage = ""
	return nil
}

// CkExpire 检测是否过期
func CkExpire() bool {
	if wails_apps.ExpireTime > 0 {
		tm, err := times.GetNowTime()
		if err != nil {
			return true
		}
		if tm > wails_apps.ExpireTime {
			IsExpire = true
			return IsExpire
		}
	}
	IsExpire = false
	return IsExpire
}

// BackgroundCheck 业务入口必须检测
func BackgroundCheck() *wails_core.Result {
	if IsRegistered == false {
		msg := "请先注册软件"
		if IsRegisterMessage != "" {
			msg = IsRegisterMessage
		}
		return wails_core.Wrong(9999, msg, nil)
	}
	if CkExpire() == true {
		return wails_core.Wrong(9998, "程序已过期", nil)
	}
	return nil
}
